﻿#include "Camera_onvif.h"

Camera_onvif::Camera_onvif(int id)
{
	camera_id = id;

	cv::FileStorage fs("camera.yml", cv::FileStorage::READ);
	if (fs.isOpened()) {
		cv::FileNode fn = fs["camera_1"];
		std::string uri = fn["snap_uri"];
		camera_snap_uri = QString::fromLatin1(uri.data());
	}
}

Camera_onvif::~Camera_onvif()
{
}

void Camera_onvif::snap()
{
	if (_busy) return;

	qDebug() << "抓拍开始" << Qt::endl;
	busy(true);
	g_counter.start();

	QNetworkRequest r;
	r.setUrl(QUrl(camera_snap_uri));
	QNetworkAccessManager* manager = new QNetworkAccessManager();
	manager->setTransferTimeout(1000);
	reply = manager->get(r);

	//摘要认证
	connect(manager, &QNetworkAccessManager::authenticationRequired, this, [=](QNetworkReply* reply, QAuthenticator* authenticator) {
		authenticator->setUser("admin");
		authenticator->setPassword("admin12345");
		});

	connect(reply, &QNetworkReply::finished, this, [=]() {
		QByteArray all = reply->readAll();
		if (!all.isNull()) {
			std::vector<uchar> buf;
			int len = all.size();
			for (int i = 0;i < len;i++)
				buf.push_back(all[i]);
			//decode
			cv::Mat img = cv::imdecode(buf, 0);
			emit sign_snap_rev(img);
		}
		busy(false);
		elapsed("抓拍结束");

		});

	connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply) {
		auto err = reply->error();
		qDebug() << QString("manager finished, error:%1").arg(err) << Qt::endl;
		busy(false);
		});

}

void Camera_onvif::busy(bool state)
{
	this->_busy = state;
}

void Camera_onvif::elapsed(QString msg)
{
	qDebug() << msg << g_counter.elapsed() << Qt::endl;
}
